package cfgloader

import (
	"bufio"
	"bytes"
	"errors"
	"os"
	"runtime"
	"strings"
)

var (
	commentStr = "#"
)

func init() {
    if runtime.GOOS == "windows" {
		commentStr = ";"
	}
}

// Configuration 配置
type configuration struct {
	values map[string]string
}

// LoadConfigFromFile 从文件读取配置
func LoadConfigFromFile(filename string) (*configuration, error) {
	fd, err := os.Open(filename)
	if err != nil {
		return nil, err
	}
	defer fd.Close()
	reader := bufio.NewReader(fd)
	scanner := bufio.NewScanner(reader)
	var buffer bytes.Buffer

	for scanner.Scan() {
		buffer.WriteString(scanner.Text())
		buffer.WriteString("\n")
	}

	return LoadConfig(buffer.String())
}

// LoadConfig 从字符串中读取配置
func LoadConfig(cfg string) (*configuration, error) {
	lines := strings.Split(cfg, "\n")
	ret := configuration{}
	ret.values = map[string]string{}
	var section string
	for _, line := range lines {
		trimmed := strings.TrimSpace(line)
		if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
			section = trimmed[1 : len(trimmed)-1]
			continue
		}

		if len(trimmed) > 0 {
			if strings.HasPrefix(trimmed, commentStr) {
				continue
			}
			assignIndex := strings.Index(trimmed, "=")
			if assignIndex == -1 {
				return nil, errors.New("invalid config at line '" + line + "'")
			}
			key := strings.TrimSpace(trimmed[0:assignIndex])
			value := strings.TrimSpace(trimmed[assignIndex+1:])
			ret.values[section+"."+key] = value
		}
	}
	return &ret, nil
}

// Get 根据 section 和 key 获取 value
func (c *configuration) Get(section string, key string) string {
	if c == nil {
		return ""
	}
	return c.values[section+"."+key]
}
